package cn.hd01.web.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hd01.repository.entity.IntegrationRule;
import cn.hd01.service.IntegrationRuleService;
import cn.hd01.web.auth.Auth;
import cn.hd01.web.util.WebException;

@Controller
@RequestMapping("/integrationRule")
@Auth
public class IntegrationRuleController {
	
	@Autowired
	private IntegrationRuleService integrationRuleService;
	
	@RequestMapping(method = RequestMethod.GET)
	public String index(Model m, HttpServletRequest request) {
		return "integrationRule";
	}

	@ResponseBody
	@RequestMapping(path = "/list", method = RequestMethod.GET)
	private Page<IntegrationRule> find(IntegrationRule ir, @PageableDefault Pageable pageable) {
		return integrationRuleService.findAll(ir, pageable); 
	}

	@ResponseBody
	@RequestMapping(path = "/save", method = RequestMethod.POST)
	private void save(IntegrationRule ir) {

		validateIntegrationRule(ir);
		
		IntegrationRule rule = null;
		if(ir.getId() != null){
			rule = integrationRuleService.findOne(ir.getId());
			rule.setRuleName(ir.getRuleName());
			rule.setIntegration(ir.getIntegration());
			rule.setUpdateTime(new Date());
		}else{
			Date date = new Date();
			ir.setCreateTime(date);
			ir.setUpdateTime(date);
			rule = ir;
		}
		
		integrationRuleService.save(rule);
	}
	
	private void validateIntegrationRule(IntegrationRule ir){
		
		if(StringUtils.isEmpty(ir.getRuleName())){
			throw new WebException(HttpStatus.BAD_REQUEST, "规则名字不能为空");
		}
		
		if(ir.getIntegration() == null){
			throw new WebException(HttpStatus.BAD_REQUEST, "积分不能为空");
		}
		
	}
}
